using Microsoft.EntityFrameworkCore;
using Project_Schedule.Configures;
using Project_Schedule.Domain.BackGround.com.core.dto;
using Project_Schedule.Domain.BackGround.com.core.Interface;
using Project_Schedule.Domain.BackGround.com.core.utils;
using Project_Schedule.Domain.Request;
using Project_Schedule.Model;
using Project_Schedule.Utilities;
using static System.Threading.Tasks.Task;

namespace Project_Schedule.Domain.BackGround.com.core.Service;

public class Bg_RefuseWebErrorMessageService : IBackgroundRefuseUserSendMessage
{
    public async Task<JRequest> SendErrorMessage(BackgroundRefuseUserErrorString dto)
    {
        try
        {
            var errorCode = System_ErrorCodeCreate.CreateCodeErrorUsedQuery(dto.Account!);
            await using var db = new DataDbContext();
            var info = await db.SystemUsers?.FirstOrDefaultAsync(e => e.Account == dto.Account);
            if (info is null) throw new Exception("发送提示流程：接收者账户错误");
            info.ErrorCode = errorCode;
            await db.SaveChangesAsync();
            await Run(() =>
            {
                try
                {
                    var content = $"错误流程：=》{dto.Message}/n,请使用ErrorCode：{errorCode} 进行查询更改";
                    var time = DateTime.Now.ToString("u");
                    MailHelper.Send($"{time}-账户申请错误提示：", content, dto.Email!);
                }
                catch (Exception ex)
                {
                    _logHelper.LogError(ex);
                }
            });
            return JRequest.Ok(true);
        }
        catch (Exception exception)
        {
            _logHelper.LogError(exception);
            return JRequest.Ok(false, false, exception.Message);
        }
    }

    private readonly INLogHelper _logHelper;

    public Bg_RefuseWebErrorMessageService(INLogHelper logHelper)
    {
        _logHelper = logHelper;
    }
}